package io.adminboot.system.interceptor;

import io.adminboot.contrant.AppContextConst;
import io.adminboot.entity.User;
import io.adminboot.exception.MyException;
import io.adminboot.manager.TokenManager;
import io.adminboot.system.annotation.Login;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限(Token)验证
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

	@Value("${myapp.api.tokenParamName}")
	private String tokenParamName;

	@Autowired
	private TokenManager tokenManager;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		Login annotation;
		if (handler instanceof HandlerMethod) {
			annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
		} else {
			return true;
		}

		if (annotation == null) {
			return true;
		}

		// 获取用户凭证
		String token = request.getHeader(tokenParamName);
		if (StringUtils.isBlank(token)) {
			token = request.getParameter(tokenParamName);
		}

		// 凭证为空
		if (StringUtils.isBlank(token)) {
			throw new MyException(tokenParamName + "不能为空", HttpStatus.UNAUTHORIZED.value());
		}

		User user = tokenManager.getUserByToken(token);

		if (user == null) {
			throw new MyException(tokenParamName + "失效，请重新登录", HttpStatus.UNAUTHORIZED.value());
		}

		// 设置userId到request里，后续根据userId，获取用户信息
		request.setAttribute(AppContextConst.CURRENT_USER_ATTRIBUTE, user);

		return true;
	}
}
